//
//  calendarViewController.m
//  myselfTest
//
//  Created by Lucifer on 15-5-21.
//  Copyright (c) 2015年 xuxzhou. All rights reserved.
//

#import "calendarViewController.h"
#import "WeightItem.h"
#import "WeightDB.h"
#import "UIView+Helper.h"
#import "borkenLineViewController.h"
@interface calendarViewController ()<UITextFieldDelegate>
@property(nonatomic,strong)WeightDB * weightDateB;
@property(nonatomic,strong)NSMutableArray * weightDataArray;
@property(nonatomic,strong)UILabel * dateLabel;
@property(nonatomic,strong)UITextField * weightTF;
@property(nonatomic,strong)UITextField * eatKcalTF;
@property(nonatomic,strong)UITextField * sportKaclTF;
@property(nonatomic,strong)UIButton * submintButton;
@property(nonatomic,strong)UIButton * gotoTodayButton;
@property(nonatomic,strong)NSDateFormatter *dateFormatter;
@property(nonatomic,strong)WeightItem * weightItem;
@property(nonatomic,strong)UIButton * brokenLineButton;
@end

@implementation calendarViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.calendar reloadData]; // Must be call in viewDidAppear
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self bulidweightDB];
    [self buildUI];
    
}

#pragma mark - DB
-(void)bulidweightDB{
    WeightDB * db =[[WeightDB alloc]init];
    [db createDataBase];
    _weightDateB=[[WeightDB alloc] init];
    _weightDataArray = [NSMutableArray arrayWithArray:[_weightDateB findWithUid:nil limit:10000]];
    
}
-(void)changeWeightItemForPage:(NSString *)date{
    _weightItem =[_weightDateB findWithNoteDate:date];
    if (_weightItem) {
        _dateLabel.text=date;
        _weightTF.text=_weightItem.weightKG;
        _eatKcalTF.text=_weightItem.eatKcal;
        _sportKaclTF.text=_weightItem.sportKcal;
    }
}

-(void)buildUI{
    
    UILabel  * dateLabelH =[[UILabel alloc]initWithFrame:CGRectMake(10, 0, CGRectGetWidth(self.view.frame)*0.4, 20)];
    dateLabelH .text=@"当前选择时间:";
    dateLabelH.font=[UIFont systemFontOfSize:18];
    dateLabelH.textColor=[UIColor blackColor];
    [self.view addSubview:dateLabelH];
    [self.view addSubview:dateLabelH];
    
    
    _dateLabel=[[UILabel alloc]initWithFrame:CGRectMake(dateLabelH.endPointX+1, 0, CGRectGetWidth(self.view.frame)-10, 22)];
    _dateLabel.font=[UIFont systemFontOfSize:18];
        NSString *dateNow = [_dateFormatter stringFromDate:[NSDate date]];
    _dateLabel.text=[NSString stringWithFormat:@"%@",dateNow];

    [self.view addSubview:_dateLabel];
    UILabel  * weightLabel =[[UILabel alloc]initWithFrame:CGRectMake(10, _dateLabel.endPointY+5, CGRectGetWidth(self.view.frame)*0.4, 20)];
    weightLabel .text=@"体重（KG）:";
    weightLabel.font=[UIFont systemFontOfSize:18];
    weightLabel.textColor=[UIColor blackColor];
    [self.view addSubview:weightLabel];

    
    _weightTF=[[UITextField alloc]initWithFrame:CGRectMake(weightLabel.endPointX+1,_dateLabel.endPointY+5, CGRectGetWidth(self.view.frame)*0.5, 20)];
    _weightTF.delegate=self;
    _weightTF.inputAccessoryView = ({
        UIToolbar *numberToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
        numberToolbar.barStyle = UIBarStyleDefault;
        numberToolbar.items = @[[[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelNumberPad)],
                                [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                                [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)]];
        [numberToolbar sizeToFit];
        numberToolbar;
    });
    _weightTF.keyboardType=UIKeyboardTypeNumberPad;
    _weightTF.placeholder=@"输入当日体重";
    [self.view addSubview:_weightTF];
    
    
    
    UILabel  * eatKaclTF =[[UILabel alloc]initWithFrame:CGRectMake(10, weightLabel.endPointY+5, CGRectGetWidth(self.view.frame)*0.4, 20)];
    eatKaclTF .text=@"摄入千卡(Kcal):";
    eatKaclTF.font=[UIFont systemFontOfSize:18];
    eatKaclTF.textColor=[UIColor blackColor];
    [self.view addSubview:eatKaclTF];

    _eatKcalTF=[[UITextField alloc]initWithFrame:CGRectMake(eatKaclTF.endPointX+5, eatKaclTF.startPointY, CGRectGetWidth(self.view.frame)*0.5, 20)];
    _eatKcalTF.delegate=self;
    _eatKcalTF.keyboardType=UIKeyboardTypeNumberPad;
    _eatKcalTF.inputAccessoryView = ({
        UIToolbar *numberToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
        numberToolbar.barStyle = UIBarStyleDefault;
        numberToolbar.items = @[[[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelNumberPad)],
                                [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                                [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)]];
        [numberToolbar sizeToFit];
        numberToolbar;
    });
    
    _eatKcalTF.placeholder=@"输入当日摄入千卡";
    [self.view addSubview:_eatKcalTF];

    UILabel  * sportKcal =[[UILabel alloc]initWithFrame:CGRectMake(10, eatKaclTF.endPointY+5, CGRectGetWidth(self.view.frame)*0.4, 20)];
    sportKcal .text=@"运动消耗(Kcal):";
    sportKcal.font=[UIFont systemFontOfSize:18];
    sportKcal.textColor=[UIColor blackColor];
    [self.view addSubview:sportKcal];
    
    _sportKaclTF=[[UITextField alloc]initWithFrame:CGRectMake(sportKcal.endPointX+5, sportKcal.startPointY, CGRectGetWidth(self.view.frame)*0.5, 20)];
    _sportKaclTF.delegate=self;
    _sportKaclTF.keyboardType=UIKeyboardTypeNumberPad;
    _sportKaclTF.inputAccessoryView = ({
        UIToolbar *numberToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
        numberToolbar.barStyle = UIBarStyleDefault;
        numberToolbar.items = @[[[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelNumberPad)],
                                [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                                [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)]];
        [numberToolbar sizeToFit];
        numberToolbar;
    });
    
    _sportKaclTF.placeholder=@"输入运动消耗千卡";
    [self.view addSubview:_sportKaclTF];
    
    
    _submintButton=[[UIButton alloc]initWithFrame:CGRectMake(0, _sportKaclTF.endPointY+10, CGRectGetWidth(self.view.frame), 44)];
    [_submintButton setTitle:@"保存数据" forState:UIControlStateNormal];
    [_submintButton setBackgroundColor:[UIColor lightGrayColor]];
    [_submintButton addTarget:self action:@selector(submintButtonClikced) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_submintButton];
    
    _brokenLineButton=[UIButton buttonWithType:UIButtonTypeCustom];
    _brokenLineButton.frame=CGRectMake(0, 0, 66, 44);
    [_brokenLineButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_brokenLineButton setTitle:@"折线图" forState:UIControlStateNormal];
    UIBarButtonItem * leftButton=[[UIBarButtonItem alloc]initWithCustomView:_brokenLineButton];
    [self.navigationItem setRightBarButtonItem:leftButton];
    [_brokenLineButton addTarget:self action:@selector(brokenLineButtonclicked) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self buildCalender];

    //    查找今天是否填写
    _dateFormatter = [[NSDateFormatter alloc] init];
    [_dateFormatter setDateFormat:@"YYYY-MM-dd"];
    dateNow = [_dateFormatter stringFromDate:[NSDate date]];
    [self changeWeightItemForPage:dateNow];

}
-(void)buildCalender{
    self.calendar = [JTCalendar new];
    _calendarMenuView=[[JTCalendarMenuView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.frame)-400-64, CGRectGetWidth(self.view.frame), 50)];
    [self.view addSubview:_calendarMenuView];
    _calendarContentView=[[JTCalendarContentView alloc]initWithFrame:CGRectMake(0,_calendarMenuView.endPointY, CGRectGetWidth(self.view.frame), 300)];
    [self.view addSubview:_calendarContentView];
    // All modifications on calendarAppearance have to be done before setMenuMonthsView and setContentView
    // Or you will have to call reloadAppearance
    {
        self.calendar.calendarAppearance.calendar.firstWeekday = 2; // Sunday == 1, Saturday == 7
        self.calendar.calendarAppearance.dayCircleRatio = 9. / 10.;
        self.calendar.calendarAppearance.ratioContentMenu = 1.;
    }
    [self.calendar setMenuMonthsView:self.calendarMenuView];
    [self.calendar setContentView:self.calendarContentView];
    [self.calendar setDataSource:self];
    
    _gotoTodayButton=[[UIButton alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.frame)-64-44, CGRectGetWidth(self.view.frame), 44)];
    [_gotoTodayButton setTitle:@"返回今天" forState:UIControlStateNormal];
    [_gotoTodayButton setBackgroundColor:[UIColor lightGrayColor]];
    [_gotoTodayButton addTarget:self action:@selector(gotoTodayButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_gotoTodayButton];
    
}


#pragma mark - 各种点击
-(void)brokenLineButtonclicked{
    borkenLineViewController  * brokenline =[[borkenLineViewController alloc ]init];
    [self.navigationController pushViewController:brokenline animated:YES];


}
-(void)cancelNumberPad{
    [self.view endEditing:YES];
}
-(void)doneWithNumberPad{
    [self.view endEditing:YES];
}
-(void)gotoTodayButtonClicked{
    [self.calendar setCurrentDate:[NSDate date]];
}
-(void)submintButtonClikced{
    if (_weightTF.text.length!=0) {
        WeightItem * weightitem =[[WeightItem alloc]init];
        weightitem.notesDate=_dateLabel.text;
        weightitem.weightKG=_weightTF.text;
        weightitem.eatKcal=_eatKcalTF.text;
        weightitem.sportKcal=_sportKaclTF.text;
         [_weightDateB saveWeightItem:weightitem];//增加
    }
}
#pragma mark - JTCalendarDataSource

- (BOOL)calendarHaveEvent:(JTCalendar *)calendar date:(NSDate *)date
{
    if ([self islaterDateThatNow:date]!=1) {
        NSString *dateS = [_dateFormatter stringFromDate:date];
        NSLog(@"dateSdateSdateSdateSdateS           %@",dateS);
         WeightItem * item=[_weightDateB findWithNoteDate:dateS];
        if ([item.notesDate isEqualToString:dateS]) {
            
            return 1;
        }
        
        return 0;
    }
    return 0;
}
-(int)islaterDateThatNow:(NSDate * )date{
    NSString *dateSMS = [_dateFormatter stringFromDate:date];
    NSDate *now = [NSDate date];
    NSString *dateNow = [_dateFormatter stringFromDate:now];
    NSDate * dateD =[_dateFormatter dateFromString:dateSMS];
    NSDate * nowD =[_dateFormatter dateFromString:dateNow]; 
    NSComparisonResult result = [dateD compare:nowD];
    if (result == NSOrderedDescending) {
//        NSLog(@"startTime  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
//        NSLog(@"startTime is in the past");
        return -1;
    }
//      NSLog(@"Both dates are the same");
    return 0;
}

- (void)calendarDidDateSelected:(JTCalendar *)calendar date:(NSDate *)date
{
    
    NSString *dateStr = [_dateFormatter stringFromDate:date];
    _dateLabel.text=[NSString stringWithFormat:@"%@",dateStr];

    [self changeWeightItemForPage:dateStr];
}

#pragma mark - Transition examples

- (void)transitionExample
{
    CGFloat newHeight = 300;
    if(self.calendar.calendarAppearance.isWeekMode){
        newHeight = 75.;
    }
    
    [UIView animateWithDuration:.5
                     animations:^{
                         self.calendarContentViewHeight.constant = newHeight;
                         [self.view layoutIfNeeded];
                     }];
    
    [UIView animateWithDuration:.25
                     animations:^{
                         self.calendarContentView.layer.opacity = 0;
                     }
                     completion:^(BOOL finished) {
                         [self.calendar reloadAppearance];
                         
                         [UIView animateWithDuration:.25
                                          animations:^{
                                              self.calendarContentView.layer.opacity = 1;
                                          }];
                     }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
